#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, os, stat
from pathlib import Path as ph
import shutil

class DirNode:

    def __init__(self, path: ph):
        self.path = path
        self.parent = None
        self.child_dirs = []
        self.is_empty = True

    def __str__(self):
        return str(self.path) + ":> " + ("empty" if self.is_empty else "notEmtpy")

def scan_dir(dir_node):

    dir_is_empty = True

    for child in dir_node.path.iterdir():
        if child.is_dir():
            child_node = DirNode(child)
            child_node.parent = dir_node
            dir_node.child_dirs.append(child_node)
            scan_dir(child_node)
        else:
            is_hidden = child.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN
            if not is_hidden or child.suffix != '.torrent':
                dir_is_empty = False
    
    if not dir_is_empty:
        cur = dir_node
        while cur is not None:
            cur.is_empty = False
            cur = cur.parent

def print_dir_node(dir_node: DirNode):
    print(dir_node)
    if len(dir_node.child_dirs) > 0:
        for child in dir_node.child_dirs:
            print_dir_node(child)

def remove_empty_nodes(dir_node: DirNode):
    for child in dir_node.child_dirs:
        remove_empty_nodes(child)
    if dir_node.is_empty:
        print('remove', dir_node.path)
        shutil.rmtree(str(dir_node.path))

if __name__ == '__main__':

    work_dir = sys.argv[1]
    pHead = ph(work_dir)

    if not pHead.is_dir():
        print('目标不是文件夹！')
        sys.exit(1)

    head = DirNode(pHead)
    scan_dir(head)

    # print_dir_node(head)
    remove_empty_nodes(head)
    os.system('pause')